# Alexander F. Gazmararian
# afg2@princeton.edu

# Load packages
library(tidyverse)
library(modelsummary)

# Load data
g <- readRDS("data/NatCAPS_20220816.rds")

# Standardize covariates for table
g$Liberal <- ifelse(g$Ideo3 == "Liberal", 1, 0)
g$Conservative <- ifelse(g$Ideo3 == "Conservative", 1, 0)
g$Income <- gsub("[$]", "", g$Income)

# Get summary statistics for August
file <- "tables/tbl_summarystat_capsaugust22.txt"
datasummary(
  formula = (Age = age) + (Female)  + Black + Hispanic + (College = CollegeDegree) +
    (Democrat = Dem) + (Republican = Rep) + Liberal + Conservative + Income ~ Mean + SD + N + Percent(),
  data = g,
  fmt = 2,
  escape = FALSE,
  output = "latex"
) %>%
  cat(., file = file)
# Trim table shell
tbl <- readLines(file)
tbl <- tbl[-c(1,2,length(tbl))]
cat(tbl, file = file)


# Load overnight data
g2 <- readRDS("data/NatCAPS_20220822.rds")
g2$Liberal <- ifelse(g2$Ideo3 == "Liberal", 1, 0)
g2$Conservative <- ifelse(g2$Ideo3 == "Conservative", 1, 0)
g2$Income <- gsub("[$]", "", g2$Income)
# Create table
file <- "tables/tbl_summarystat_capsaugustovernight22.txt"
datasummary(
  formula = (Age = age) + (Female)  + Black + Hispanic + (College = CollegeDegree) +
    (Democrat = Dem) + (Republican = Rep) + Liberal + Conservative + Income ~ Mean + SD + N + Percent(),
  data = g2,
  fmt = 2,
  escape = FALSE,
  output = "latex"
) %>%
  cat(., file = file)
# Trim table shell
tbl <- readLines(file)
tbl <- tbl[-c(1,2,length(tbl))]
cat(tbl, file = file)


# Load October data
g3 <- readRDS("data/NatCAPS_20221013.rds")
g3$Income <- gsub("[$]", "", g3$Income)
# Create table
file <- "tables/tbl_summarystat_capsoctt22.txt"
datasummary(
  formula = (Age = age) + (Female)  + Black + Hispanic + (College = CollegeDegree) +
    (Democrat = Dem) + (Republican = Rep) + (Rural = rural) + Income ~ Mean + SD + N + Percent(),
  data = g3,
  fmt = 2,
  escape = FALSE,
  output = "latex"
) %>%
  cat(., file = file)
# Trim table shell
tbl <- readLines(file)
tbl <- tbl[-c(1,2,length(tbl))]
cat(tbl, file = file)

# Load September data
g4 <- readRDS("data/NatCAPS_20220928.rds")
g4$Income <- gsub("[$]", "", g4$Income)
# Create table
file <- "tables/tbl_summarystat_capssept22.txt"
datasummary(
  formula = (Age = age) + (Female)  + Black + Hispanic + (College = CollegeDegree) +
    (Democrat = Dem) + (Republican = Rep) + Income + (Rural = rural) ~ Mean + SD + N + Percent(),
  data = g4,
  fmt = 2,
  escape = FALSE,
  output = "latex"
) %>%
  cat(., file = file)
# Trim table shell
tbl <- readLines(file)
tbl <- tbl[-c(1,2,length(tbl))]
cat(tbl, file = file)

